<?php

namespace ApiBundle\Controller\V1;

use ApiBundle\Controller\BaseController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\Routing\Annotation\Route;
use FOS\RestBundle\Controller\FOSRestController;
use GamesBundle\Entity\GamesComplain;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;


class SecurityController extends BaseController
{
    /**
     * @author  coffey
     * 用户登陆
     *
     * @ApiDoc(
     *  resource=true,
     *  description="用户登陆接口",
     *  parameters={
     *      {"name"="_username", "dataType"="string","required"=true,"description"="用户名"},
     *      {"name"="_password", "dataType"="string","required"=true,"description"="用户密码"},
     *  },
     * )
     * @Rest\POST("/login")
     */
    public function loginAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $userName = $request->request->get('_username');
        $password = $request->request->get('_password');
        if (isset($userName) && isset($password)) {
            $userInfo = $em->getRepository('GamesBundle:User')->findOneBy(array('username' => $userName));
            if (!empty($userInfo)) {
                $passwordStr = $userInfo->getPassword();
                if (password_verify($password, $passwordStr)) {
                    $token = new UsernamePasswordToken($userInfo->getUsername(), $password, 'main', array('ROLE_USER'));
                    $this->get('security.token_storage')->setToken($token);
                    $token->setUser($userInfo);
                    $this->get('session')->set('_security_main', serialize($token));
                    return $this->getLogin();
                }
            }
            return $this->FinalJson(1);
        }
        return $this->FinalJson(1);
    }
}
